<template>

  <div style="display: flex;align-items: flex-end;flex-direction: column">
    <div style="width: 100%;display: flex;align-items: center;flex-direction: row;justify-content: space-between;">
      <el-button class="btn-seal" type="primary" @click="exportExcel">Download</el-button>
      <el-input
          v-model="search"
          style="max-width: 200px;margin: 5px 0;"
          placeholder="Please input"
      >
        <template #append>
          <el-button @click="SearchTable">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>
    <el-table
        id="educe-table"
        v-loading="tableloading"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ 'text-align' : 'center', 'color' : 'black'}"
        :data="tableData"
        :row-class-name="tableRowClassName"
        header-row-class-name="table-header-row"
        header-cell-class-name="table-header-cell"
        header-row-style="font-size: 18px;"
        border
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
    >
      <el-table-column
          v-for="item in column"
          sortable="custom"
          :prop="item.value"
          :label="item.name"
          :render-header="renderHeader"
          header-align="center"
          show-overflow-tooltip
          resizable
      >
        <template #default="{row}" v-if="item.href">
          <a style="color: #337ab7" @click="toDetail(row['asmid'])">{{ row[item.value]}}</a>
        </template>
        <template #default="{row}" v-if="!item.href">
          <span v-if="item.value.split('.').length==1">
            {{ row[item.value]== null || ''? 'NA' : row[item.value]}}
          </span>
          <span v-if="item.value.split('.').length==2">
              {{
                row[item.value.split('.')[0]][item.value.split('.')[1]]== null || ''? 'NA' : row[item.value.split('.')[0]][item.value.split('.')[1]]
              }}
          </span>
        </template>
      </el-table-column>
  <!--    <el-table-column v-for="item in column" sortable :prop="item.value" :label="item.name"></el-table-column>-->
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        style="margin: 5px 0"
        :page-size="size"
        :total="total"
        :current-page="currentPage"
        @current-change="handlePageChange"
    />
  </div>
</template>

<script>
import {useRouter} from "vue-router";
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx';
import api from "@/api/api";

export default {
  name: "table",
  data(){
    return {
      search:'',
      tableloading: true,
      tableData: [],
      total: null,
      size:14,
      currentPage:1,
      rsList: []
    }
  },
  props:{
    searchKey: {
      type: String,
      required: false,
      default: ''
    },
    apiKey:{
      type: String,
      required: false,
      default: ''
    },
    column:{
      type: Array,
      required: true,
      default: []
    },
    tableAllData: {
      type: Array,
      required: true
    },
  },
  watch:{
    tableAllData: {
      handler (newValue, oldValue) {
        // console.log('tableAllData==>',newValue)
        Reflect.set(this,'tableloading',true)
        Reflect.set(this,'tableAllData',newValue)
        this.gettabledataFirst()
        console.log('tableAllData==>ok')
      }
    },
  },
  mounted() {
    this.gettabledataFirst()
  },
  methods:{
    // 表头部重新渲染
    renderHeader ({ column, $index }) {
      // 新建一个 span
      const span = document.createElement('span')
      // 设置表头名称
      span.innerText = column.label
      // 临时插入 document
      document.body.appendChild(span)
      // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
      column.minWidth = span.getBoundingClientRect().width + 80
      // 移除 document 中临时的 span
      document.body.removeChild(span)
      return column.label
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex%2 === 1) {
        return 'warning-row';
      } else if (rowIndex%2 === 0) {
        return 'success-row';
      }
      return '';
    },
    getRandomString(length) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
    },
    // download
    exportExcel() {
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(this.tableAllData);

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      let name = this.getRandomString(8)
      // 导出Excel文件
      XLSX.writeFile(workbook, name+'.xlsx');
    },
    // 首次获得页面
    gettabledataFirst(){
      this.tableloading = true
      const start = this.currentPage*this.size - this.size
      const end = this.size*this.currentPage
      this.total = this.tableAllData.length
      // console.log("this.tableData =====>",this.tableAllData)
      this.tableData = this.tableAllData.slice(start,end)
      this.tableloading = false
    },
    // 更新分页
    handlePageChange(value){
      this.currentPage = value
      this.tableloading = true
      const star = this.currentPage*this.size - this.size
      const end = this.currentPage*this.size
      this.tableData = this.tableAllData.slice(star,end)
      this.tableloading = false
    },
    //Search
    SearchTable(){
      this.currentPage = 1
      this.tableloading = true
      let searchTable = []
      this.tableAllData.forEach((item) => {
        let keys = Object.keys(item)
        console.log("keys ==> ",keys)
        keys.forEach(key => {
          if(item[key]==this.search){
            searchTable.push(item)
            console.log("item[key] ==> ",item)
          }
          // console.log("item[key] ==> ",item[key])
        })
      })
      console.log("searchTable ==> ",searchTable)
      this.tableData = searchTable
      this.tableloading = false
      this.total = this.tableData.length
    }
  },
  setup(){
    const router = useRouter()

    const toDetail = (ASMID)=>{
      router.push({
        path:"/detail",
        query:{
          ASMID
        }
      })
    }

    return {
      toDetail
    }
  }
}
</script>

<style scoped>
::v-deep .el-table .warning-row {
  background: white;
  font-size: 15px
}

::v-deep .el-table .success-row {
  background: white;
  font-size: 15px
}
::v-deep .table-header-row .table-header-cell{
  background-color: #eeeeee;
}
::v-deep .table-header-row .table-header-cell .cell{
  /*White-space:nowrap;*/
}
::v-deep .el-popper{
  max-width: 400px;
}
</style>
